package com.cloud.v2.auth.service;

import com.cloud.v2.api.model.LoginUser;
import com.cloud.v2.api.openapi.RemoteUserService;
import com.cloud.v2.common.domain.R;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

/**
 * 查询用户service实现类
 * @Author FuCe
 * @Date 2020/11/17 23:22
 * @Version 1.0
 **/
@Service
public class AuthUserDetailsServiceImpl implements UserDetailsService {
    protected Logger logger = LoggerFactory.getLogger(AuthUserDetailsServiceImpl.class);

    @Resource
    private  RemoteUserService remoteUserService;




    /**
     * 通过用户名查询用户
     * @param username 用户name
     * @return UserDetails
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
       R<LoginUser> loginUser= remoteUserService.getInfo(username);
        if(loginUser==null || loginUser.getData()==null || loginUser.getData().getSysUser()==null){
            logger.debug("登录用户:"+username+"不存在");
            throw new UsernameNotFoundException("登录用户:"+username+"不存在");
        }
        LoginUser loginUser2=loginUser.getData();
        List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
       //得到用户信息
        loginUser2.getPermissions().forEach(perStr -> {
            if(perStr!=null){
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(perStr);
                grantedAuthorities.add(grantedAuthority);
            }
        } );

       return new User(loginUser2.getUsername(),loginUser2.getSysUser().getPassword() , grantedAuthorities);
    }
}
